// ui/components/App.js
import TagFilter from './TagFilter.js';
import ChatDisplayArea from './ChatDisplayArea.js';
import MessageInputArea from './MessageInputArea.js';
import RightSidebar from './RightSidebar.js';
import WhiteboardPanel from './WhiteboardPanel.js';

export default {
  name: 'App',
  components: {
    'tag-filter': TagFilter,
    'chat-display-area': ChatDisplayArea,
    'message-input-area': MessageInputArea,
    'right-sidebar': RightSidebar,
    'whiteboard-panel': WhiteboardPanel,
  },
  setup() {
    const { ref, onMounted, computed } = Vue;

    const isLoading = ref(false);
    const errorMessage = ref('');

    const initialData = ref(null);
    const activeTagsForFilter = ref([]);
    const displayedChatHistory = ref([]);
    const selectedAgentIdForLog = ref(null);

    const participantsData = computed(() => {
      return initialData.value?.participants || [];
    });

    const fullChatHistory = computed(() => {
      return initialData.value?.chat_history || [];
    });

    const whiteboardData = computed(() => {
      return initialData.value?.whiteboard_items || [];
    });

    const fetchInitialData = async (retryCount = 0) => {
      isLoading.value = true;
      errorMessage.value = '';
      const maxRetries = 10;
      const retryDelay = 500;

      try {
        if (window.pywebview?.api?.get_initial_chatroom_data &&
            typeof window.pywebview.api.get_initial_chatroom_data === 'function' &&
            window.pywebview.api.get_active_tags_for_filter &&
            typeof window.pywebview.api.get_active_tags_for_filter === 'function') {

          console.log("App.js: pywebview API and required functions seem available.");

          const data = await window.pywebview.api.get_initial_chatroom_data();
          initialData.value = data;
          console.log("App.js: Initial data loaded:", data);
          if (data && !data.error) {
            displayedChatHistory.value = fullChatHistory.value;
          } else if (data && data.error) {
            console.error("App.js: Error in initial data from API:", data.error);
            errorMessage.value = `加载初始数据失败: ${data.error}`;
          }

          const tagsFromApi = await window.pywebview.api.get_active_tags_for_filter();
          if (tagsFromApi && !tagsFromApi.error) {
            activeTagsForFilter.value = tagsFromApi.map(tag => ({
              name: tag.name,
              count: tag.count,
              selected: true
            }));
            console.log("App.js: Active tags for filter loaded:", activeTagsForFilter.value);
          } else if (tagsFromApi && tagsFromApi.error) {
            console.error('App.js: Error fetching active tags from API:', tagsFromApi.error);
            errorMessage.value = `加载标签数据失败: ${tagsFromApi.error}`;
          } else {
            console.error('App.js: Unknown error or empty response fetching active tags.');
             errorMessage.value = '加载标签数据时发生未知错误。';
          }
        } else {
          if (retryCount < maxRetries) {
            let missingReason = "pywebview API object not available.";
            if (window.pywebview && window.pywebview.api) {
                if (typeof window.pywebview.api.get_initial_chatroom_data !== 'function') {
                    missingReason = "get_initial_chatroom_data function is missing.";
                } else if (typeof window.pywebview.api.get_active_tags_for_filter !== 'function') {
                    missingReason = "get_active_tags_for_filter function is missing.";
                }
            }
            console.warn('App.js: API or functions not ready (' + missingReason + '). Retrying (' + (retryCount + 1) + '/' + maxRetries + ')...');
            setTimeout(() => fetchInitialData(retryCount + 1), retryDelay);
            return; // Important: return here to avoid finally block setting isLoading to false prematurely
          } else {
            console.error('App.js: pywebview API or required functions not available after multiple retries.');
            errorMessage.value = '加载初始数据失败，请稍后重试或检查后端连接。';
            initialData.value = { error: 'Failed to load data: API/functions not available after retries.' };
          }
        }
      } catch (error) {
        console.error('App.js: Error during fetchInitialData:', error);
        errorMessage.value = '加载初始数据失败，请稍后重试或检查后端连接。';
        initialData.value = { error: 'Failed to load data.', details: error.message };
      } finally {
        isLoading.value = false;
      }
      if (!initialData.value || initialData.value.error) {
        displayedChatHistory.value = [];
        activeTagsForFilter.value = [];
      }
    };

    onMounted(() => {
      fetchInitialData();

      // 将测试函数暴露到 window 对象，以便从控制台调用
      window.addTestMarkdownMessage = () => {
        const testMessageContent = `**加粗文本示例**
*斜体文本示例*

\`内联代码示例: const x = 10;\`

\`\`\`javascript
// 代码块示例:
function greet(name) {
  return \`Hello, \${name}!\`;
}
console.log(greet("Markdown User"));
\`\`\`

- 无序列表项 1
- 无序列表项 2
  - 嵌套列表项 2.1
  - 嵌套列表项 2.2

1. 有序列表项 A
2. 有序列表项 B

[这是一个链接到 example.com](https://www.example.com)

> 这是一个引用块。
> 它可以跨越多行。

---

水平分割线以上.`;

        const testMessage = {
          message_id: 'test-md-' + Date.now(), // 改为字符串拼接
          sender_id: 'test-sender',
          sender_nickname: 'Markdown Tester',
          content: testMessageContent,
          timestamp: new Date().toISOString(),
          tags: ['test', 'markdown']
        };
        
        // 1. Add to full history (optional for this specific test, but good for consistency)
        if (initialData.value && initialData.value.chat_history) {
            initialData.value.chat_history.push(testMessage);
        } else if (initialData.value) {
            initialData.value.chat_history = [testMessage];
        } else {
            // Should not happen if fetchInitialData ran, but as a fallback
            initialData.value = { chat_history: [testMessage], participants: [], whiteboard_items: [], global_tags: [] };
        }
        console.log('App.js: Test Markdown message pushed to initialData.value.chat_history.');

        // 2. FOR TESTING ONLY: Directly set displayedChatHistory to the new test message
        // This bypasses the handleNewMessage logic and backend filtering issues for this test.
        displayedChatHistory.value = [testMessage];
        console.log('App.js: FOR TESTING: displayedChatHistory directly set to new test message:', JSON.parse(JSON.stringify(displayedChatHistory.value)));
        
        console.log("App.js: Test Markdown message added. Check UI for rendering (bypassing filter).");
      };
      
      console.log("App.js: addTestMarkdownMessage() is now available in the browser console.");
    });

    const handleTagFilterChanged = async (selectedTagNames) => {
      console.log("App.js: Filter changed, selected tags:", selectedTagNames);
      isLoading.value = true;
      errorMessage.value = '';
      try {
        if (!selectedTagNames || selectedTagNames.length === 0) {
          displayedChatHistory.value = fullChatHistory.value;
          activeTagsForFilter.value = activeTagsForFilter.value.map(tag => ({ ...tag, selected: true }));
        } else {
          if (window.pywebview?.api?.filter_chat_history_by_tags &&
              typeof window.pywebview.api.filter_chat_history_by_tags === 'function') {
            console.log('App.js: Calling API filter_chat_history_by_tags with tags:', selectedTagNames);
            const filteredHistory = await window.pywebview.api.filter_chat_history_by_tags(selectedTagNames);
            console.log('App.js: API filter_chat_history_by_tags responded with:', JSON.parse(JSON.stringify(filteredHistory)));

            if (filteredHistory && !filteredHistory.error) {
              console.log('App.js: Applying filtered history (length: ' + filteredHistory.length + ') to displayedChatHistory.');
              displayedChatHistory.value = filteredHistory;
              console.log('App.js: (Filter branch) displayedChatHistory full content after API filter:', JSON.parse(JSON.stringify(displayedChatHistory.value)));
            } else {
              console.error('App.js: Error filtering chat history by tags:', filteredHistory ? filteredHistory.error : 'Unknown error');
              errorMessage.value = `筛选聊天记录失败: ${filteredHistory ? filteredHistory.error : '未知错误'}`;
              displayedChatHistory.value = fullChatHistory.value; // Fallback to full history on error
            }
            activeTagsForFilter.value = activeTagsForFilter.value.map(tag => ({
              ...tag,
              selected: selectedTagNames.includes(tag.name)
            }));
          } else {
            console.error('App.js: pywebview API filter_chat_history_by_tags is not a function.');
            errorMessage.value = '筛选聊天记录功能不可用。';
            displayedChatHistory.value = fullChatHistory.value; // Fallback
          }
        }
      } catch (error) {
        console.error('App.js: Error calling filter_chat_history_by_tags:', error);
        errorMessage.value = '筛选聊天记录时发生错误，请重试。';
        displayedChatHistory.value = fullChatHistory.value; // Fallback
      } finally {
        isLoading.value = false;
      }
    };

    const handleParticipantSelectedForLog = (participantId) => {
      console.log('App.js: Participant selected for log viewing in App.js:', participantId);
      selectedAgentIdForLog.value = participantId;
    };

    const handleNewMessage = (messageDetails) => {
      if (messageDetails.success && messageDetails.message) {
        const newMessage = messageDetails.message;

        if (initialData.value && initialData.value.chat_history) {
            initialData.value.chat_history.push(newMessage);
        } else if (initialData.value) {
            initialData.value.chat_history = [newMessage];
        } else {
            initialData.value = { chat_history: [newMessage], participants: [], whiteboard_items: [], global_tags: [] };
        }
        console.log('App.js: New message added to fullChatHistory:', JSON.parse(JSON.stringify(newMessage)));
        console.log('App.js: fullChatHistory length after push:', fullChatHistory.value.length);
        if (fullChatHistory.value.length > 0) {
          console.log('App.js: Last message in fullChatHistory:', JSON.parse(JSON.stringify(fullChatHistory.value[fullChatHistory.value.length - 1])));
        }

        if (newMessage.tags && newMessage.tags.length > 0) {
            const existingTagNamesInFilter = activeTagsForFilter.value.map(t => t.name);
            newMessage.tags.forEach(newMsgTagName => {
                if (!existingTagNamesInFilter.includes(newMsgTagName)) {
                    activeTagsForFilter.value.push({
                        name: newMsgTagName,
                        count: 1, 
                        selected: true 
                    });
                    console.log('App.js: New tag \'' + newMsgTagName + '\' added to activeTagsForFilter and selected.');
                } else {
                    const tagInFilter = activeTagsForFilter.value.find(t => t.name === newMsgTagName);
                    if (tagInFilter && !tagInFilter.selected) {
                        tagInFilter.selected = true;
                        console.log('App.js: Existing tag \'' + newMsgTagName + '\' in new message was not selected, now selected.');
                    }
                }
            });
        }

        let tagsToUseForFiltering = activeTagsForFilter.value
                                    .filter(t => t.selected)
                                    .map(t => t.name);
        
        if (newMessage.tags && newMessage.tags.length > 0) {
            newMessage.tags.forEach(newMsgTag => {
                if (!tagsToUseForFiltering.includes(newMsgTag)) {
                    tagsToUseForFiltering.push(newMsgTag);
                }
            });
        }
        tagsToUseForFiltering = [...new Set(tagsToUseForFiltering)];

        if (tagsToUseForFiltering.length === 0) {
            console.log("App.js: No active filters after new message, showing full history.");
            displayedChatHistory.value = fullChatHistory.value;
            console.log('App.js: (No filters branch) displayedChatHistory length after assignment:', displayedChatHistory.value.length);
            console.log('App.js: (No filters branch) displayedChatHistory message IDs:', displayedChatHistory.value.map(m => m.message_id));
            const isNewMessageDisplayed = displayedChatHistory.value.some(m => m.message_id === newMessage.message_id);
            console.log('App.js: (No filters branch) isNewMessageDisplayed:', isNewMessageDisplayed);
            if (!isNewMessageDisplayed) {
                 // This push might be problematic if fullChatHistory.value is not the same array instance as initialData.value.chat_history
                 // Vue's reactivity on arrays works best when array mutation methods (push, pop, splice, etc.) are called on the reactive array itself,
                 // or when the array is replaced entirely.
                 // Let's ensure fullChatHistory is indeed reflecting the pushed message before this branch.
                 displayedChatHistory.value.push(newMessage); // Potentially problematic if displayedChatHistory is a shallow copy
                 console.log("App.js: Pushed new message to displayedChatHistory as it was not found after assigning full history. New length:", displayedChatHistory.value.length);
            }
        } else {
            console.log("App.js: Filters active or new message tags present. Calling handleTagFilterChanged with effective tags:", JSON.parse(JSON.stringify(tagsToUseForFiltering)));
            handleTagFilterChanged(tagsToUseForFiltering);
        }

      } else if (messageDetails.success === false) {
        console.error("App.js: Message submission failed:", messageDetails.error);
        // This is where we might set errorMessage.value if MessageInputArea doesn't handle its own errors
        // For now, we expect MessageInputArea to emit 'send-error'
      }
    };

    const handleApiError = (message) => {
      errorMessage.value = message;
      // Potentially clear after a timeout
      // setTimeout(() => { errorMessage.value = ''; }, 5000);
    };

    const clearErrorMessage = () => {
      console.log('App.js: clearErrorMessage called. Current errorMessage:', errorMessage.value);
      errorMessage.value = '';
      console.log('App.js: errorMessage after clear:', errorMessage.value);
    };

    const handleWhiteboardUpdate = (newWhiteboardItems) => {
      if (initialData.value) {
        initialData.value.whiteboard_items = newWhiteboardItems;
        console.log("App.js: Whiteboard data updated by event:", newWhiteboardItems);
      } else {
        console.warn("App.js: initialData is null, cannot update whiteboard items.");
      }
    };

    const testMessage = ref('Hello from App.js setup!');

    return {
      testMessage,
      initialData,
      selectedAgentIdForLog,
      activeTagsForFilter,
      displayedChatHistory,
      participantsData,
      whiteboardData,
      isLoading,
      errorMessage,
      fetchInitialData,
      handleTagFilterChanged,
      handleParticipantSelectedForLog,
      handleNewMessage,
      handleWhiteboardUpdate,
      handleApiError,
      clearErrorMessage
    };
  },
  template: `
  <div class="app-container">
    <header class="app-header">
      <h1>LLM Chatroom MVP</h1>
      <div v-if="errorMessage" class="global-error">
        {{ errorMessage }}
        <button @click="clearErrorMessage" class="close-error-btn">X</button>
      </div>
    </header>

    <main class="main-content">
      <div class="left-sidebar-area">
        <!-- <LeftSidebar
          :participants="participantsData"
          @participant-selected="handleParticipantSelectedForLog"
        /> -->
        <whiteboard-panel
          :whiteboard-items="whiteboardData"
          @whiteboard-updated="handleWhiteboardUpdate"
          @whiteboard-error="handleApiError"
          class="whiteboard-section"
        />
        <!-- <p>Left Sidebar Area (Components Commented Out)</p> -->
      </div>

      <div class="center-column-area">
        <p>{{ testMessage }}</p> <!-- Test message display -->
        <tag-filter :active-tags="activeTagsForFilter" @filter-changed="handleTagFilterChanged" />
        <chat-display-area :chat-history="displayedChatHistory" />
        <message-input-area @message-sent="handleNewMessage" @send-error="handleApiError" />
        <!-- <p>Center Column Area (Components Commented Out)</p> -->
      </div>

      <div class="right-sidebar-area">
        <right-sidebar
          :participants="participantsData"
          :selected-agent-id-for-thought-viewer="selectedAgentIdForLog"
          @select-agent-for-thoughts="handleParticipantSelectedForLog"
          @log-error="handleApiError"
        />
        <!-- <p>Right Sidebar Area (Components Commented Out)</p> -->
      </div>
    </main>

    <footer class="app-footer">
      <p>Status: {{ initialData ? (initialData.error && !errorMessage ? initialData.error : (isLoading ? '加载中...' : '已加载')) : (isLoading ? '加载中...' : '等待数据...') }}</p>
      <!-- <pre>{{ initialData }}</pre> -->
    </footer>

  </div>
  `
};